<template>
  <div class="grade-list">
    <div class="page-title">成绩管理</div>
    
    <!-- 搜索表单 -->
    <a-card class="search-form mb-16">
      <a-form
        ref="searchFormRef"
        :model="searchForm"
        layout="inline"
        @finish="handleSearch"
      >
        <a-form-item label="学生姓名" name="studentName">
          <a-input
            v-model:value="searchForm.studentName"
            placeholder="请输入学生姓名"
            allow-clear
          />
        </a-form-item>
        
        <a-form-item label="学号" name="studentId">
          <a-input
            v-model:value="searchForm.studentId"
            placeholder="请输入学号"
            allow-clear
          />
        </a-form-item>
        
        <a-form-item label="课程" name="courseId">
          <a-select
            v-model:value="searchForm.courseId"
            placeholder="请选择课程"
            allow-clear
            style="width: 150px"
          >
            <a-select-option
              v-for="course in courseList"
              :key="course.id"
              :value="course.id"
            >
              {{ course.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="班级" name="classId">
          <a-select
            v-model:value="searchForm.classId"
            placeholder="请选择班级"
            allow-clear
            style="width: 150px"
          >
            <a-select-option
              v-for="cls in classList"
              :key="cls.id"
              :value="cls.id"
            >
              {{ cls.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="考试类型" name="examType">
          <a-select
            v-model:value="searchForm.examType"
            placeholder="请选择考试类型"
            allow-clear
            style="width: 120px"
          >
            <a-select-option value="midterm">期中考试</a-select-option>
            <a-select-option value="final">期末考试</a-select-option>
            <a-select-option value="quiz">随堂测验</a-select-option>
            <a-select-option value="assignment">作业</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="考试日期" name="examDateRange">
          <a-range-picker
            v-model:value="searchForm.examDateRange"
            format="YYYY-MM-DD"
            style="width: 200px"
          />
        </a-form-item>
        
        <a-form-item>
          <a-space>
            <a-button type="primary" html-type="submit" :loading="loading">
              <template #icon>
                <SearchOutlined />
              </template>
              搜索
            </a-button>
            <a-button @click="handleReset">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>
    
    <!-- 操作按钮 -->
    <div class="action-buttons mb-16">
      <a-space>
        <a-button type="primary" @click="handleAdd">
          <template #icon>
            <PlusOutlined />
          </template>
          录入成绩
        </a-button>
        
        <a-button type="primary" ghost @click="handleBatchAdd">
          <template #icon>
            <FileAddOutlined />
          </template>
          批量录入
        </a-button>
        
        <a-button
          type="primary"
          ghost
          :disabled="!selectedRowKeys.length"
          @click="handleBatchDelete"
        >
          <template #icon>
            <DeleteOutlined />
          </template>
          批量删除
        </a-button>
        
        <a-button @click="handleStatistics">
          <template #icon>
            <BarChartOutlined />
          </template>
          成绩统计
        </a-button>
        
        <a-button @click="handleExport">
          <template #icon>
            <ExportOutlined />
          </template>
          导出成绩
        </a-button>
      </a-space>
    </div>
    
    <!-- 成绩列表表格 -->
    <a-card class="data-table">
      <a-table
        :columns="columns"
        :data-source="gradeList"
        :loading="loading"
        :pagination="pagination"
        :row-selection="rowSelection"
        :scroll="{ x: 1400 }"
        @change="handleTableChange"
      >
        <!-- 学生信息列 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'student'">
            <a-space>
              <a-avatar :size="32">
                <template #icon>
                  <UserOutlined />
                </template>
              </a-avatar>
              <div>
                <div class="student-name">{{ record.studentName }}</div>
                <div class="student-id">{{ record.studentId }}</div>
              </div>
            </a-space>
          </template>
          
          <!-- 考试类型列 -->
          <template v-else-if="column.key === 'examType'">
            <a-tag :color="getExamTypeColor(record.examType)">
              {{ getExamTypeText(record.examType) }}
            </a-tag>
          </template>
          
          <!-- 成绩列 -->
          <template v-else-if="column.key === 'score'">
            <div class="score-display">
              <span :class="getScoreClass(record.score, record.fullScore)">
                {{ record.score }}
              </span>
              <span class="full-score">/ {{ record.fullScore }}</span>
            </div>
          </template>
          
          <!-- 等级列 -->
          <template v-else-if="column.key === 'grade'">
            <a-tag :color="getGradeColor(record.score, record.fullScore)">
              {{ getGradeText(record.score, record.fullScore) }}
            </a-tag>
          </template>
          
          <!-- 排名列 -->
          <template v-else-if="column.key === 'rank'">
            <a-tag color="purple">
              第{{ record.classRank }}名
            </a-tag>
          </template>
          
          <!-- 操作列 -->
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleEdit(record)">
                编辑
              </a-button>
              <a-button type="link" size="small" @click="handleViewDetail(record)">
                详情
              </a-button>
              <a-popconfirm
                title="确定要删除这条成绩记录吗？"
                @confirm="handleDelete(record)"
              >
                <a-button type="link" size="small" danger>
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
    
    <!-- 成绩录入弹窗 -->
    <a-modal
      v-model:open="gradeFormVisible"
      :title="isEdit ? '编辑成绩' : '录入成绩'"
      width="600px"
      @ok="handleGradeFormSubmit"
      @cancel="gradeFormVisible = false"
    >
      <a-form
        ref="gradeFormRef"
        :model="gradeForm"
        :rules="gradeRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="学生" name="studentId">
          <a-select
            v-model:value="gradeForm.studentId"
            placeholder="请选择学生"
            show-search
            :filter-option="filterStudent"
          >
            <a-select-option
              v-for="student in studentList"
              :key="student.id"
              :value="student.id"
            >
              {{ student.name }} ({{ student.studentId }})
            </a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="课程" name="courseId">
          <a-select
            v-model:value="gradeForm.courseId"
            placeholder="请选择课程"
          >
            <a-select-option
              v-for="course in courseList"
              :key="course.id"
              :value="course.id"
            >
              {{ course.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="考试类型" name="examType">
          <a-select
            v-model:value="gradeForm.examType"
            placeholder="请选择考试类型"
          >
            <a-select-option value="midterm">期中考试</a-select-option>
            <a-select-option value="final">期末考试</a-select-option>
            <a-select-option value="quiz">随堂测验</a-select-option>
            <a-select-option value="assignment">作业</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="考试日期" name="examDate">
          <a-date-picker
            v-model:value="gradeForm.examDate"
            placeholder="请选择考试日期"
            style="width: 100%"
            format="YYYY-MM-DD"
          />
        </a-form-item>
        
        <a-form-item label="满分" name="fullScore">
          <a-input-number
            v-model:value="gradeForm.fullScore"
            :min="1"
            :max="200"
            placeholder="请输入满分"
            style="width: 100%"
          />
        </a-form-item>
        
        <a-form-item label="得分" name="score">
          <a-input-number
            v-model:value="gradeForm.score"
            :min="0"
            :max="gradeForm.fullScore || 100"
            :precision="1"
            placeholder="请输入得分"
            style="width: 100%"
          />
        </a-form-item>
        
        <a-form-item label="备注" name="remarks">
          <a-textarea
            v-model:value="gradeForm.remarks"
            placeholder="请输入备注信息"
            :rows="3"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import dayjs from 'dayjs'
import {
  SearchOutlined,
  ReloadOutlined,
  PlusOutlined,
  FileAddOutlined,
  DeleteOutlined,
  BarChartOutlined,
  ExportOutlined,
  UserOutlined
} from '@ant-design/icons-vue'

const router = useRouter()

// 表单引用
const searchFormRef = ref()
const gradeFormRef = ref()

// 加载状态
const loading = ref(false)

// 成绩表单弹窗显示状态
const gradeFormVisible = ref(false)

// 是否为编辑模式
const isEdit = ref(false)

// 搜索表单
const searchForm = reactive({
  studentName: '',
  studentId: '',
  courseId: undefined,
  classId: undefined,
  examType: undefined,
  examDateRange: null
})

// 成绩表单
const gradeForm = reactive({
  id: null,
  studentId: undefined,
  courseId: undefined,
  examType: undefined,
  examDate: null,
  fullScore: 100,
  score: null,
  remarks: ''
})

// 成绩表单验证规则
const gradeRules = {
  studentId: [{ required: true, message: '请选择学生', trigger: 'change' }],
  courseId: [{ required: true, message: '请选择课程', trigger: 'change' }],
  examType: [{ required: true, message: '请选择考试类型', trigger: 'change' }],
  examDate: [{ required: true, message: '请选择考试日期', trigger: 'change' }],
  fullScore: [{ required: true, message: '请输入满分', trigger: 'blur' }],
  score: [{ required: true, message: '请输入得分', trigger: 'blur' }]
}

// 选中的行
const selectedRowKeys = ref([])

// 课程列表
const courseList = ref([
  { id: '1', name: '语文' },
  { id: '2', name: '数学' },
  { id: '3', name: '英语' },
  { id: '4', name: '物理' },
  { id: '5', name: '化学' }
])

// 班级列表
const classList = ref([
  { id: 'class1', name: '一年级1班' },
  { id: 'class2', name: '一年级2班' },
  { id: 'class3', name: '二年级1班' },
  { id: 'class4', name: '二年级2班' }
])

// 学生列表
const studentList = ref([
  { id: '1', name: '张三', studentId: 'S2024001' },
  { id: '2', name: '李四', studentId: 'S2024002' },
  { id: '3', name: '王五', studentId: 'S2024003' },
  { id: '4', name: '赵六', studentId: 'S2024004' }
])

// 成绩列表
const gradeList = ref([
  {
    id: '1',
    studentId: 'S2024001',
    studentName: '张三',
    courseId: '1',
    courseName: '语文',
    className: '一年级1班',
    examType: 'midterm',
    examDate: '2024-11-15',
    score: 85.5,
    fullScore: 100,
    classRank: 5,
    gradeRank: 12,
    teacherName: '王老师',
    remarks: '表现良好'
  },
  {
    id: '2',
    studentId: 'S2024001',
    studentName: '张三',
    courseId: '2',
    courseName: '数学',
    className: '一年级1班',
    examType: 'midterm',
    examDate: '2024-11-16',
    score: 92.0,
    fullScore: 100,
    classRank: 2,
    gradeRank: 8,
    teacherName: '李老师',
    remarks: '计算能力强'
  },
  {
    id: '3',
    studentId: 'S2024002',
    studentName: '李四',
    courseId: '1',
    courseName: '语文',
    className: '一年级1班',
    examType: 'midterm',
    examDate: '2024-11-15',
    score: 78.0,
    fullScore: 100,
    classRank: 8,
    gradeRank: 25,
    teacherName: '王老师',
    remarks: '需要加强阅读理解'
  },
  {
    id: '4',
    studentId: 'S2024003',
    studentName: '王五',
    courseId: '3',
    courseName: '英语',
    className: '二年级1班',
    examType: 'final',
    examDate: '2024-12-20',
    score: 88.5,
    fullScore: 100,
    classRank: 3,
    gradeRank: 15,
    teacherName: '张老师',
    remarks: '口语表达优秀'
  }
])

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 4,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
})

// 表格列配置
const columns = [
  {
    title: '学生信息',
    key: 'student',
    width: 150,
    fixed: 'left'
  },
  {
    title: '课程',
    dataIndex: 'courseName',
    key: 'courseName',
    width: 100
  },
  {
    title: '班级',
    dataIndex: 'className',
    key: 'className',
    width: 120
  },
  {
    title: '考试类型',
    key: 'examType',
    width: 100,
    align: 'center'
  },
  {
    title: '考试日期',
    dataIndex: 'examDate',
    key: 'examDate',
    width: 120
  },
  {
    title: '成绩',
    key: 'score',
    width: 100,
    align: 'center'
  },
  {
    title: '等级',
    key: 'grade',
    width: 80,
    align: 'center'
  },
  {
    title: '班级排名',
    key: 'rank',
    width: 100,
    align: 'center'
  },
  {
    title: '任课教师',
    dataIndex: 'teacherName',
    key: 'teacherName',
    width: 100
  },
  {
    title: '备注',
    dataIndex: 'remarks',
    key: 'remarks',
    width: 150,
    ellipsis: true
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right'
  }
]

// 行选择配置
const rowSelection = computed(() => ({
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys) => {
    selectedRowKeys.value = keys
  }
}))

// 获取考试类型颜色
const getExamTypeColor = (type) => {
  const colorMap = {
    midterm: 'blue',
    final: 'red',
    quiz: 'green',
    assignment: 'orange'
  }
  return colorMap[type] || 'default'
}

// 获取考试类型文本
const getExamTypeText = (type) => {
  const textMap = {
    midterm: '期中考试',
    final: '期末考试',
    quiz: '随堂测验',
    assignment: '作业'
  }
  return textMap[type] || '未知'
}

// 获取成绩样式类
const getScoreClass = (score, fullScore) => {
  const percentage = (score / fullScore) * 100
  if (percentage >= 90) return 'score-excellent'
  if (percentage >= 80) return 'score-good'
  if (percentage >= 70) return 'score-fair'
  if (percentage >= 60) return 'score-pass'
  return 'score-fail'
}

// 获取等级颜色
const getGradeColor = (score, fullScore) => {
  const percentage = (score / fullScore) * 100
  if (percentage >= 90) return 'red'
  if (percentage >= 80) return 'orange'
  if (percentage >= 70) return 'blue'
  if (percentage >= 60) return 'green'
  return 'default'
}

// 获取等级文本
const getGradeText = (score, fullScore) => {
  const percentage = (score / fullScore) * 100
  if (percentage >= 90) return '优秀'
  if (percentage >= 80) return '良好'
  if (percentage >= 70) return '中等'
  if (percentage >= 60) return '及格'
  return '不及格'
}

// 学生筛选
const filterStudent = (input, option) => {
  const student = studentList.value.find(s => s.id === option.value)
  if (!student) return false
  return student.name.toLowerCase().includes(input.toLowerCase()) ||
         student.studentId.toLowerCase().includes(input.toLowerCase())
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadGradeList()
}

// 重置搜索
const handleReset = () => {
  searchFormRef.value.resetFields()
  pagination.current = 1
  loadGradeList()
}

// 录入成绩
const handleAdd = () => {
  isEdit.value = false
  resetGradeForm()
  gradeFormVisible.value = true
}

// 批量录入
const handleBatchAdd = () => {
  message.info('批量录入功能开发中...')
}

// 编辑成绩
const handleEdit = (record) => {
  isEdit.value = true
  Object.assign(gradeForm, {
    ...record,
    examDate: record.examDate ? dayjs(record.examDate) : null
  })
  gradeFormVisible.value = true
}

// 查看详情
const handleViewDetail = (record) => {
  message.info('查看详情功能开发中...')
}

// 删除成绩
const handleDelete = async (record) => {
  try {
    // 调用删除API
    // await gradeApi.deleteGrade(record.id)
    
    message.success('删除成功')
    loadGradeList()
  } catch (error) {
    message.error('删除失败')
  }
}

// 批量删除
const handleBatchDelete = () => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除选中的 ${selectedRowKeys.value.length} 条成绩记录吗？`,
    onOk: async () => {
      try {
        // 调用批量删除API
        // await gradeApi.batchDeleteGrades(selectedRowKeys.value)
        
        message.success('批量删除成功')
        selectedRowKeys.value = []
        loadGradeList()
      } catch (error) {
        message.error('批量删除失败')
      }
    }
  })
}

// 成绩统计
const handleStatistics = () => {
  message.info('成绩统计功能开发中...')
}

// 导出成绩
const handleExport = () => {
  message.info('导出功能开发中...')
}

// 提交成绩表单
const handleGradeFormSubmit = async () => {
  try {
    await gradeFormRef.value.validate()
    
    const submitData = {
      ...gradeForm,
      examDate: gradeForm.examDate ? dayjs(gradeForm.examDate).format('YYYY-MM-DD') : null
    }
    
    if (isEdit.value) {
      // 更新成绩
      // await gradeApi.updateGrade(gradeForm.id, submitData)
      message.success('成绩更新成功')
    } else {
      // 添加成绩
      // await gradeApi.addGrade(submitData)
      message.success('成绩录入成功')
    }
    
    gradeFormVisible.value = false
    loadGradeList()
  } catch (error) {
    console.error('提交失败:', error)
  }
}

// 重置成绩表单
const resetGradeForm = () => {
  Object.assign(gradeForm, {
    id: null,
    studentId: undefined,
    courseId: undefined,
    examType: undefined,
    examDate: null,
    fullScore: 100,
    score: null,
    remarks: ''
  })
}

// 表格变化处理
const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  loadGradeList()
}

// 加载成绩列表
const loadGradeList = async () => {
  try {
    loading.value = true
    
    // 构建查询参数
    const params = {
      ...searchForm,
      examStartDate: searchForm.examDateRange?.[0] ? dayjs(searchForm.examDateRange[0]).format('YYYY-MM-DD') : null,
      examEndDate: searchForm.examDateRange?.[1] ? dayjs(searchForm.examDateRange[1]).format('YYYY-MM-DD') : null,
      page: pagination.current,
      pageSize: pagination.pageSize
    }
    
    // 调用API获取数据
    // const response = await gradeApi.getGradeList(params)
    // gradeList.value = response.data
    // pagination.total = response.total
    
    console.log('加载成绩列表', params)
  } catch (error) {
    message.error('加载成绩列表失败')
  } finally {
    loading.value = false
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadGradeList()
})
</script>

<style scoped>
.grade-list {
  padding: 0;
}

.search-form {
  border-radius: 8px;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.data-table {
  border-radius: 8px;
}

.student-name {
  font-weight: 500;
  color: #333;
}

.student-id {
  font-size: 12px;
  color: #999;
}

.score-display {
  display: flex;
  align-items: center;
  justify-content: center;
}

.score-excellent {
  color: #f5222d;
  font-weight: bold;
  font-size: 16px;
}

.score-good {
  color: #fa8c16;
  font-weight: bold;
  font-size: 16px;
}

.score-fair {
  color: #1890ff;
  font-weight: 500;
  font-size: 16px;
}

.score-pass {
  color: #52c41a;
  font-size: 16px;
}

.score-fail {
  color: #999;
  font-size: 16px;
}

.full-score {
  color: #999;
  font-size: 12px;
  margin-left: 2px;
}

@media (max-width: 768px) {
  .action-buttons {
    flex-direction: column;
  }
  
  .action-buttons .ant-btn {
    width: 100%;
  }
}
</style>